<template>
  <view class="container">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view>
      <view>
        <!-- 	<image src="/static/images/loading.gif"></image> -->
        <uv-swiper
          class="bg"
          height="300"
          imgMode="aspectFill"
          keyName="image"
          :list="listAds"
          indicatorMode="dot"
          indicatorStyle="bottom"
        ></uv-swiper>
      </view>
      <view style="background-color: #ffffff; padding: 30rpx">
        <view>{{ getFoodName(goodDetail.storeName) }}</view>
        <view class="font-small text-light-black mt-1"
          >{{ currentLanguageTexts.sold }}{{ goodDetail.sales }}</view
        >
        <view class="mt-1 flex justify-between">
          <view style="color: red">${{ goodDetail.price }}</view>
          <view>
            <view
              class="btn-group"
              v-if="
                goodDetail.stock > 0 &&
                goodDetail.productAttr.length >= 1 &&
                goodDetail.productAttr[0].attrValues != '默认'
              "
            >
              <button
                type="primary"
                class="btn property_btn"
                hover-class="none"
                size="mini"
                @tap="showGoodDetailModal(goodDetail)"
              >
                {{ currentLanguageTexts.selectSpecifications }}
              </button>
              <view class="dot" v-show="goodCartNum(goodDetail.id)">
                {{ goodCartNum(goodDetail.id) }}</view
              >
            </view>
            <view
              class="btn-group"
              v-if="
                goodDetail.stock > 0 &&
                goodDetail.productAttr.length == 1 &&
                goodDetail.productAttr[0].attrValues == '默认'
              "
            >
              <button
                type="default"
                v-show="goodCartNum(goodDetail.id)"
                plain
                class="btn reduce_btn"
                size="mini"
                hover-class="none"
                @tap="handleReduceFromCart(goodDetail)"
              >
                <view class="iconfont iconsami-select"></view>
              </button>
              <view class="number" v-show="goodCartNum(goodDetail.id)">{{
                goodCartNum(goodDetail.id)
              }}</view>
              <button
                type="primary"
                v-show="goodCartNum(goodDetail.id) == 0"
                class="btn property_btn"
                size="min"
                hover-class="none"
                @tap="handleAddToCart(goodDetail, 1)"
              >
                <span class="iconfont iconadd-select"></span>
                {{ currentLanguageTexts.addToCart }}
              </button>
              <button
                type="primary"
                class="btn add_btn"
                v-show="goodCartNum(goodDetail.id)"
                size="min"
                hover-class="none"
                @tap="handleAddToCart(goodDetail, 1)"
              >
                <view class="iconfont iconadd-select"></view>
              </button>
            </view>
            <view v-if="goodDetail.stock == 0">{{
              currentLanguageTexts.soldOut
            }}</view>
          </view>
        </view>
      </view>
      <view
        style="background-color: #ffffff; padding: 30rpx; margin-top: 10rpx"
      >
        <view class="mb-3">{{ currentLanguageTexts.productDetails }}</view>
        <view style="font-size: 22rpx"
          ><rich-text :nodes="goodDetail.description"></rich-text
        ></view>
      </view>

      <modal
        :show="goodDetailModalVisible"
        class="good-detail-modal"
        color="#5A5B5C"
        width="90%"
        custom
        padding="0rpx"
        radius="12rpx"
      >
        <view class="cover">
          <view class="btn-group">
            <image
              src="/static/images/menu/close.png"
              @tap="closeGoodDetailModal"
            ></image>
          </view>
        </view>
        <scroll-view class="detail" scroll-y>
          <!-- 	<view v-if="good.image" class="image">
						<image :src="good.image"></image>
					</view> -->

          <view class="wrapper">
            <view class="basic">
              <view class="name">{{ getFoodName(good.storeName) }}</view>
              <view class="tips flex justify-between">{{
                good.storeInfo
              }}</view>
            </view>
            <view class="properties">
              <view
                class="property"
                v-for="(item, index) in good.productAttr"
                :key="index"
              >
                <view class="title">
                  <text class="name">{{ item.attrName }}</text>
                </view>
                <view class="values">
                  <view
                    class="value"
                    v-for="(value, key) in item.attrValueArr"
                    :key="key"
                    :class="{ default: value == newValue[index] }"
                    @tap="changePropertyDefault(index, key, false)"
                  >
                    {{ value }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="action">
          <view class="left">
            <view class="price">￥{{ good.price }}</view>
            <view class="props">
              {{ good.valueStr }}
            </view>
          </view>
          <view class="btn-group">
            <text style="margin-right: 20rpx"
              >{{ currentLanguageTexts.inventory }}：{{ good.stock }}
            </text>
            <button
              type="default"
              plain
              class="btn"
              size="mini"
              hover-class="none"
              @tap="handlePropertyReduce"
            >
              <view class="iconfont iconsami-select"></view>
            </button>
            <view class="number">{{ good.number }}</view>
            <button
              type="primary"
              class="btn"
              size="min"
              hover-class="none"
              @tap="handlePropertyAdd"
            >
              <view class="iconfont iconadd-select"></view>
            </button>
          </view>
        </view>
        <view class="add-to-cart-btn" @tap="handleAddToCartInModal">
          <view>{{ currentLanguageTexts.addToCart }}</view>
        </view>
      </modal>

      <view class="cart-box">
        <view class="mark">
          <image src="/static/images/menu/cart.png" class="cart-img"></image>
          <view class="tag">{{ getCartGoodsNumber }}</view>
        </view>
        <view class="price">￥{{ getCartGoodsPrice }}</view>
        <button
          type="primary"
          class="pay-btn"
          @tap="toPay"
          :disabled="disabledPay"
        >
          {{
            disabledPay ? `差${spread}元起送` : currentLanguageTexts.goSettle
          }}
        </button>
      </view>
    </view>
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { formatDateTime, prePage } from '@/utils/util';
import { getFoodName } from '@/utils';
import { goodsDetail } from '@/api/goods';
const main = useMainStore();

const { orderType, store, isLogin, desk, isScan, currentLanguageTexts } =
  storeToRefs(main);
const title = ref(currentLanguageTexts.value.details);
const listAds = ref([]);
const goodDetail = ref({});
const cart = ref([]);
const good = ref({});
const goodDetailModalVisible = ref(false);
const newValue = ref([]);
const uToast = ref();
const goodCartNum = computed(() => {
  //计算单个饮品添加到购物车的数量
  return (id) =>
    cart.value.reduce((acc, cur) => {
      if (cur.id === id) {
        return (acc += cur.number);
      }
      return acc;
    }, 0);
});
const getCartGoodsNumber = computed(() => {
  //计算购物车总数
  return cart.value.reduce((acc, cur) => acc + cur.number, 0);
});
const getCartGoodsPrice = computed(() => {
  //计算购物车总价
  let price = cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
  return parseFloat(price).toFixed(2);
});
const disabledPay = computed(() => {
  //是否达到起送价
  return orderType.value == 'takeout' &&
    getCartGoodsPrice < parseFloat(store.value.min_price)
    ? true
    : false;
});
onLoad((option) => {
  detail(option.id);
});
const detail = async (id) => {
  goodDetail.value = await goodsDetail(id);
  setGoodsDetail(goodDetail.value);
  listAds.value = goodDetail.value.sliderImage.split(',');
  cart.value = uni.getStorageSync('cart') || [];
};

/**
 * 处理商品详情逻辑
 * @param detail
 */
const setGoodsDetail = (detail) => {
  goodDetail.value.description = detail.description.replace(
    /<img /g,
    "<img style='width:100%;' "
  );
};

const handleAddToCart = (newGood, num) => {
  //添加到购物车

  const index = cart.value.findIndex((item) => {
    if (newGood) {
      return item.id === newGood.id && item.props_text === good.value.valueStr;
    } else {
      return item.id === newGood.id;
    }
  });
  if (index > -1) {
    cart.value[index].number += num;
  } else {
    cart.value.push({
      id: newGood.id,
      cate_id: parseInt(newGood.cateId),
      name: newGood.storeName,
      price: newGood.price,
      number: num,
      image: newGood.image,
      valueStr: good.value.valueStr,
    });
  }
  uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));
};

const handleReduceFromCart = (good) => {
  const index = cart.value.findIndex((item) => item.id === good.id);
  cart.value[index].number -= 1;
  if (cart.value[index].number <= 0) {
    cart.value.splice(index, 1);
  }
  uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));
};

const showGoodDetailModal = (newGood) => {
  //isCartShow.value = true
  good.value = JSON.parse(
    JSON.stringify({
      ...newGood,
      number: 1,
    })
  );
  //category.value = JSON.parse(JSON.stringify(item))
  goodDetailModalVisible.value = true;
  changePropertyDefault(0, 0, true);
};

const changePropertyDefault = (index, key, isDefault) => {
  //改变默认属性值
  let valueStr = '';

  if (isDefault) {
    newValue.value = [];
    for (let i = 0; i < good.value.productAttr.length; i++) {
      newValue.value[i] = good.value.productAttr[i].attrValueArr[0];
    }
  } else {
    newValue.value[index] = good.value.productAttr[index].attrValueArr[key];
  }
  valueStr = newValue.value.join(',');

  let productValue = good.value.productValue[valueStr];
  if (!productValue) {
    let skukey = JSON.parse(JSON.stringify(newValue.value));
    skukey.sort((a, b) => a.localeCompare(b));
    valueStr = skukey.join(',');
    productValue = good.value.productValue[valueStr];
  }
  good.value.number = 1;
  good.value.price = parseFloat(productValue.price).toFixed(2);
  good.value.stock = productValue.stock;
  good.value.image = productValue.image ? productValue.image : good.value.image;
  good.value.valueStr = valueStr;
};

const handleAddToCartInModal = () => {
  if (good.value.stock <= 0) {
    uToast.value.show({
      message: currentLanguageTexts.value.insufficientInventory,
      type: 'error',
    });
    return;
  }
  handleAddToCart(good.value, good.value.number);
  closeGoodDetailModal();
};

const closeGoodDetailModal = () => {
  //关闭饮品详情模态框
  goodDetailModalVisible.value = false;
  good.value = {};
};
const handlePropertyAdd = () => {
  good.value.number += 1;
};
const handlePropertyReduce = () => {
  if (good.value.number === 1) return;
  good.value.number -= 1;
};

const toPay = () => {
  if (!isLogin.value) {
    uni.navigateTo({
      url: '/pages/components/pages/login/login',
    });
    return;
  } else {
    if (store.value.status == 0) {
      uToast.value.show({
        message: currentLanguageTexts.value.storeCloseDown,
        type: 'error',
      });
      return;
    }
    if (store.value.status == 0) {
      uToast.value.show({
        message: currentLanguageTexts.value.NotHours,
        type: 'error',
      });
      return;
    }
    // 判断当前是否在配送范围内
    if (
      orderType.value == 'takeout' &&
      store.value.distance < store.value.far
    ) {
      uToast.value.show({
        message: currentLanguageTexts.value.addressNotWithinDiliveryRange,
        type: 'error',
      });
      return;
    }

    uni.showLoading({
      title: currentLanguageTexts.value.loading,
    });
    uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));

    uni.navigateTo({
      url: '/pages/components/pages/pay/pay',
    });
  }

  uni.hideLoading();
};
</script>

<style lang="scss">
.bg {
  width: 100%;
  height: 330rpx;
}
.btn {
  padding: 0 50rpx;
}

.cart-box {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  height: 96rpx;
  border-radius: 48rpx;
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 9999;

  .cart-img {
    width: 96rpx;
    height: 96rpx;
    position: relative;
    margin-top: -48rpx;
  }

  .pay-btn {
    height: 100%;
    padding: 0 30rpx;
    color: rgb(90, 91, 92);
    border-radius: 0 50rpx 50rpx 0;
    display: flex;
    align-items: center;
    font-size: $font-size-base;
    background-color: $color-primary;
  }

  .mark {
    padding-left: 46rpx;
    margin-right: 30rpx;
    position: relative;

    .tag {
      //background-color: $color-warning;
      background-color: #ffcc00;
      color: $text-color-white;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: $font-size-sm;
      position: absolute;
      right: -10rpx;
      top: -50rpx;
      border-radius: 100%;
      padding: 4rpx;
      width: 40rpx;
      height: 40rpx;
      opacity: 0.9;
    }
  }

  .price {
    flex: 1;
    color: $text-color-base;
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;

  .btn {
    padding: 0 20rpx;
    box-sizing: border-box;
    font-size: $font-size-sm;
    height: 44rpx;
    line-height: 44rpx;

    &.property_btn {
      border-radius: 24rpx;
      background: $color-primary;
      color: rgb(90, 91, 92);
    }

    &.add_btn,
    &.reduce_btn {
      padding: 0;
      width: 44rpx;
      border-radius: 44rpx;
    }
    &.add_btn {
      background-color: $color-primary;
      color: rgb(90, 91, 92);
    }
  }

  .dot {
    position: absolute;
    background-color: #ffffff;
    border: 1px solid $color-primary;
    color: $color-primary;
    font-size: $font-size-sm;
    width: 36rpx;
    height: 36rpx;
    line-height: 36rpx;
    text-align: center;
    border-radius: 100%;
    right: -12rpx;
    top: -10rpx;
  }

  .number {
    width: 44rpx;
    height: 44rpx;
    line-height: 44rpx;
    text-align: center;
  }
}

.good-detail-modal {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .cover {
    height: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .btn-group {
      position: absolute;
      right: 10rpx;
      top: 0rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;
      z-index: 210;

      image {
        width: 80rpx;
        height: 80rpx;
      }
    }
  }

  .detail {
    width: 100%;
    min-height: 1vh;
    max-height: calc(90vh - 320rpx - 80rpx - 120rpx);
    position: relative;

    .image {
      display: flex;
      justify-content: center;
      align-items: center;
      image {
        width: 260rpx;
        height: 260rpx;
      }
    }
    .wrapper {
      width: 100%;
      height: 100%;
      overflow: hidden;

      .basic {
        padding: 0 20rpx 30rpx;
        display: flex;
        flex-direction: column;
        .name {
          font-size: $font-size-base;
          color: $text-color-base;
          margin-bottom: 10rpx;
        }
        .tips {
          font-size: $font-size-sm;
          color: $text-color-grey;
        }
      }

      .properties {
        width: 100%;
        border-top: 2rpx solid $bg-color-grey;
        padding: 10rpx 30rpx 0;
        display: flex;
        flex-direction: column;

        .property {
          width: 100%;
          display: flex;
          flex-direction: column;
          margin-bottom: 30rpx;
          padding-bottom: -16rpx;

          .title {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 20rpx;

            .name {
              font-size: 26rpx;
              color: $text-color-base;
              margin-right: 20rpx;
            }

            .desc {
              flex: 1;
              font-size: $font-size-sm;
              color: $color-primary;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .values {
            width: 100%;
            display: flex;
            flex-wrap: wrap;

            .value {
              border-radius: 8rpx;
              background-color: $bg-color-grey;
              padding: 16rpx 30rpx;
              font-size: 26rpx;
              color: $text-color-assist;
              margin-right: 16rpx;
              margin-bottom: 16rpx;

              &.default {
                background-color: $color-primary;
                color: $text-color-white;
              }
            }
          }
        }
      }
    }
  }

  .action {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: $bg-color-grey;
    height: 120rpx;
    padding: 0 26rpx;

    .left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-right: 20rpx;
      overflow: hidden;

      .price {
        font-size: $font-size-lg;
        color: $text-color-base;
      }

      .props {
        color: $text-color-assist;
        font-size: 24rpx;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .btn-group {
      display: flex;
      align-items: center;
      justify-content: space-around;

      .number {
        font-size: $font-size-base;
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        text-align: center;
      }

      .btn {
        padding: 0;
        font-size: $font-size-base;
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        border-radius: 100%;
      }
    }
  }

  .add-to-cart-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: $color-primary;
    color: $text-color-white;
    font-size: $font-size-base;
    height: 80rpx;
    border-radius: 0 0 12rpx 12rpx;
  }
}
</style>
